﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Net;

using EnvironmentalMonitor.Support.Device.Handler;
using EnvironmentalMonitor.Support.Device;
using EnvironmentalMonitor.Support.Instruction.In.Request;
using EnvironmentalMonitor.Support.Instruction.In.Response;
using EnvironmentalMonitor.Support.Instruction.Out.Request;
using EnvironmentalMonitor.Support.Instruction.Out.Response;
using EnvironmentalMonitor.Support.Instruction;
using EnvironmentalMonitor.Support.Business.Environmental;
using EnvironmentalMonitor.Support.Business;
using EnvironmentalMonitor.Support.Module;
using EnvironmentalMonitor.Support.Resource;

namespace EnvironmentalMonitor.WebApplication.Environmental.Machine.Setup
{
    public partial class ThresholdSaveJson : EnvironmentalMonitor.WebApplication.Abstract.AbstractSetupSaveJson
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            const string GUID = "guid";

            const string IP = "ip";
            const string INTERVAL_CACHE = "intervalCache";

            EnvironmentalMonitor.Support.Module.Manage.User sessionUser = this.Session[Constant.SESSION_KEY_USER] as EnvironmentalMonitor.Support.Module.Manage.User;
            DateTime now = DateTime.Now;

            EnvironmentalMonitor.Support.Module.Environmental.Machine module = new Support.Module.Environmental.Machine();
            module.Guid = this.ParameterString(GUID);
            module.UpdateUserId = sessionUser.Guid;
            module.UpdateTime = now;

            module.Ip = this.ParameterString(IP);
            module.IntervalCache = this.ParameterInt(INTERVAL_CACHE, 0);

            IPAddress ip = IPAddress.Any;

            bool ipRight = IPAddress.TryParse(module.Ip, out ip);
            bool serialRight = true;

            DetectorBusiness detectorBusiness = new DetectorBusiness();
            List<EnvironmentalMonitor.Support.Module.Environmental.Detector> modules = detectorBusiness.QueryValidityByMachine(module.Guid);
            if ((modules != null) && (modules.Count > 0))
            {
                for (int i = 0; i < modules.Count; i++)
                {
                    if (modules[i].Serial != (i + 1))
                    {
                        serialRight = false;
                        break;
                    }
                }
            }
            else
            {
                serialRight = false;
            }

            this.SaveJsonData = new Abstract.SaveJsonData();
            if ((ipRight) && (serialRight))
            {
                this.SaveJsonData.success = false;
                this.SaveJsonData.msg = "设置操作错误！";

                List<ThresholdInstruction> instructions = new List<ThresholdInstruction>();
                int rowCount = Constant.FRAME_DATA_MAXIMUM / EnvironmentalMonitor.Support.Module.Environmental.DetectorType.VALUE_LENGTH;
                int count = modules.Count / rowCount;
                if ((modules.Count % rowCount) > 0)
                {
                    count++;
                }
                List<EnvironmentalMonitor.Support.Module.Environmental.Detector>[] detectors = new List<Support.Module.Environmental.Detector>[count];
                for (int i = 0; i < detectors.Length; i++)
                {
                    detectors[i] = new List<Support.Module.Environmental.Detector>();
                    for (int j = (i * rowCount); ((j < modules.Count) && (j < (i + 1) * rowCount)); j++)
                    {
                        detectors[i].Add(modules[j]);
                    }
                    ThresholdInstruction instruction = new ThresholdInstruction(detectors[i]);
                    instructions.Add(instruction);
                }

                for (int i = 0; i < instructions.Count; i++)
                {
                    instructions[i].Count = (byte)(instructions.Count - 1);
                    instructions[i].Serial = (byte)i;
                    byte[] values = instructions[i].Encode();
                    Terminal.Run(module.Ip, values);

                    Nullable<bool> result = this.QueryTask(module.Ip, typeof(ThresholdSuccessInstruction).FullName, typeof(ThresholdErrorInstruction).FullName, now);

                    if (result != null)
                    {
                        this.SaveJsonData.success = result.Value;
                    }
                    else
                    {
                        this.SaveJsonData.success = false;
                    }
                    if (!this.SaveJsonData.success)
                    {
                        break;
                    }
                }
                if (this.SaveJsonData.success)
                {
                    this.SaveJsonData.msg = "设置操作成功！";
                }
                else
                {
                    this.SaveJsonData.msg = "设置操作失败！";
                }
            }
            else
            {
                this.SaveJsonData.success = false;
                this.SaveJsonData.msg = "设置操作参数无效！";
            }

            string json = this.Json();

            this.Response.Write(json);
            this.Response.Flush();
            this.Response.End();
        }
    }
}